package com.southwind.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.southwind.common.Cache;
import com.southwind.common.MessagePageModel;
import com.southwind.common.ResultObj;
import com.southwind.entity.Admin;
import com.southwind.entity.Message;
import com.southwind.entity.User;
import com.southwind.mapper.AdminMapper;
import com.southwind.mapper.UserMapper;
import com.southwind.service.MessageService;
import com.southwind.vo.MessageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/list")
    public Map list(MessagePageModel messagePageModel){
        Page<Message> page = new Page<>(messagePageModel.getPage(), messagePageModel.getLimit());
        Page<Message> resultPage = this.messageService.page(page);
        List<MessageVO> list = new ArrayList<>();
        for (Message record : resultPage.getRecords()) {
            MessageVO messageVO = new MessageVO();
            messageVO.setId(record.getId());
            messageVO.setDate(record.getDate());
            messageVO.setUsername(this.userMapper.getNameById(record.getUid()));
            messageVO.setAdminname(this.adminMapper.getNameById(record.getAid()));
            messageVO.setContent(record.getContent());
            messageVO.setAdmincontent(record.getAdmincontent());
            messageVO.setAdmindate(record.getAdmindate());
            list.add(messageVO);
        }
        Map map = new HashMap();
        map.put("count", resultPage.getTotal());
        map.put("data", list);
        return map;
    }

    @PostMapping("/add")
    public ResultObj add(@RequestBody Message message){
        User user = (User) Cache.map.get("user");
        message.setUid(user.getId());
        boolean save = this.messageService.save(message);
        if(save) return ResultObj.MESSAGE_ADD_SUCCESS;
        return ResultObj.MESSAGE_ADD_ERROR;
    }

    @PostMapping("/reply")
    public ResultObj reply(@RequestBody Message message){
        Admin admin = (Admin) Cache.map.get("user");
        message.setAid(admin.getId());
        message.setAdmincontent(message.getAdmincontent());
        boolean save = this.messageService.updateById(message);
        if(save) return ResultObj.REPLY_ADD_SUCCESS;
        return ResultObj.REPLY_ADD_ERROR;
    }

}

